package com.zros.modules.business.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zros.common.api.vo.PageResult;
import com.zros.common.api.vo.Result;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.business.entity.Channel;
import com.zros.modules.business.entity.Keyword;
import com.zros.modules.business.entity.Modle;
import com.zros.modules.business.service.IKeywordService;
import com.zros.modules.business.service.IModleService;
import com.zros.modules.business.vo.KeywordVo;
import com.zros.modules.business.vo.ModleVo;
import com.zros.modules.system.dto.UserInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lvkai
 * @since 2020-04-21
 */
@RestController
@RequestMapping("/business/modle")
public class ModleController {

    @Autowired
    private IModleService modleService;

    @Autowired
    private IKeywordService keywordService;

    /**
     * 分页查询商铺
     */
    @ApiOperation(value = "分页查询商铺")
    @RequiresPermissions("business:modle:list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public PageResult<ModleVo> queryPageList(HttpServletRequest request, Page<ModleVo> page, Modle modle)
    {
        //获取当前用户
        UserInfo currentUser = new UserInfo();

        Page<ModleVo> pageModle = modleService.queryList(page, modle);
        List<ModleVo> modleVoList = pageModle.getRecords();
        Long modleId = 0L;
        for (ModleVo modlevo : modleVoList) {
            modleId = modlevo.getModleId();
            Keyword keyword = new Keyword();
            keyword.setModleId(modleId);
            List<KeywordVo> keywordVos = keywordService.qryKeywordByModleId(keyword);
            modlevo.setKeyWords(keywordVos);
        }
        //PageResult<ModleVo> pageResult = new PageResult<ModleVo>(pageModle.getTotal(), pageModle.getRecords());
        PageResult<ModleVo> pageResult = new PageResult<ModleVo>(pageModle.getTotal(), modleVoList);
        return pageResult;
    }

    /**
     * 添加模板
     */
    @ApiOperation(value = "添加模板")
    @RequiresPermissions("business:modle:list")
    @PostMapping("/create")
    public Result<?> create(@RequestBody Modle modle)
    {
        try {
            List<Keyword> keywords = modle.getKeywords();
            modleService.save(modle);
            for (Keyword keyword : keywords) {
                keywordService.save(keyword);
            }
            return new Result<>().success("添加成功");
        }
        catch (Exception e) {
            return new Result<>().error("添加失败，请重试");
        }
    }
}
